package com.stop.think.service;

import com.stop.think.dao.MemberDao;
import com.stop.think.dao.SendSmsMsgErrorDao;
import com.stop.think.dao.ShopDao;
import com.stop.think.dao.entity.Member;
import com.stop.think.dao.entity.SendSmsMsgError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author zhaolipeng
 */
@Slf4j
@Service
public class BetterThinkService {

  @Resource private ShopDao shopDao;
  @Resource private MemberDao memberDao;
  @Resource private HttpSendSmsMessage httpSendSmsMessage;
  @Resource private AsyncBetterThinkService asyncBetterThinkService;
  @Resource private SendSmsMsgErrorDao sendSmsMsgErrorDao;

  public void canUseSendSmsMessage() {
    shopDao.findAll().forEach(shop -> {
      String telNums = memberDao
          .findByShopId(shop.getId())
          .stream()
          .map(Member::getTelNum)
          .collect(Collectors.joining(","));
      httpSendSmsMessage.batchSendMessage("祝你生日快乐！", telNums);
    });
  }

  public void eachOtherSendSmsMessage() {
    CountDownLatch latch = new CountDownLatch((int) shopDao.count());
    shopDao.findAll().forEach(shop -> {
      asyncBetterThinkService.sendSmsMessage(shop.getId(), latch);
    });
    try {
      latch.await();
    } catch (InterruptedException e) {
      log.error("线程在等待时被中断", e);
    }
  }

  public void errorSendSmsMessage() {
    CountDownLatch latch = new CountDownLatch((int) shopDao.count());
    shopDao.findAll().forEach(shop -> {
      try {
        asyncBetterThinkService.errorRetrySendSmsMessage(shop.getId(), latch);
      } catch (Exception e) {
        // 发生非第三方错误是保存错误日志
        SendSmsMsgError error = new SendSmsMsgError();
        error.setReason("xxxx");
        error.setShopId(shop.getId());
      }
    });
    try {
      latch.await();
    } catch (InterruptedException e) {
      log.error("线程在等待时被中断", e);
    }
  }

  public List<SendSmsMsgError> listByShopId(String shopId) {
    return new ArrayList<>();
  }

  public void handleRetry(String msgErrorId) {
    sendSmsMsgErrorDao.findById(msgErrorId).ifPresent(sendSmsMsgError -> {
      String telNums = memberDao
          .findByShopId(sendSmsMsgError.getShopId())
          .stream()
          .map(Member::getTelNum)
          .collect(Collectors.joining(","));
      httpSendSmsMessage.batchSendMessage("祝你生日快乐！", telNums);
    });
  }
}
